import datetime

import akshare as ak
import pandas as pd
import requests
from retry import retry

from python_quant.common.code import code_to_sz_sh_symbol, symbol_remove_SZ_SH, symbol_remove_SZ_SH_front, \
    code_remove_sz_sh_symbol
from python_quant.common.common import xue_qiu_board, ths_billboard


def xue_qiu_up_rate():
    """
    雪球飙升榜
    :return:
    """
    url = 'https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=1&size=100&order=desc&order_by=rank_change' \
          '&_=1658982281667&type=hot_delta&x=0.5 '
    return xue_qiu_board(url)


def xue_qiu_hot_search_24h():
    """
    雪球24小时热搜
    :return:
    """
    url = 'https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=1&size=100&order=desc&order_by=value&_=1659000252347&type=hot_24h&x=0.5'
    return xue_qiu_board(url)


def xue_qiu_hot_search_1h():
    """
    雪球1小时热搜
    :return:
    """
    url = 'https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=1&size=100&order=desc&order_by=value&_=1659000252347&type=hot_1h&x=0.5'
    return xue_qiu_board(url)


def xue_qiu_hot_discuss():
    """
    雪球热评
    :return:
    """
    url = 'https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=1&size=100&order=desc&order_by=value&_=1659000478931&type=hot_tweet&x=0.5'
    return xue_qiu_board(url)


def baidu_hot_search_today():
    now_date = datetime.datetime.now().strftime('%Y%m%d')
    stock_hot_search_baidu_df = stock_hot_search_baidu(symbol="A股", date=now_date, time="0")
    stocks = stock_hot_search_baidu_df['市场代码'].tolist()
    codes = list()
    for stock in stocks:
        code = symbol_remove_SZ_SH(stock)
        codes.append(code)
    return codes


def stock_hot_search_baidu(symbol: str = "A股", date: str = "20221014", time: str = "0"):
    """
    百度股市通-热搜股票
    https://gushitong.baidu.com/expressnews
    :param symbol: choice of {"全部", "A股", "港股", "美股"}
    :type symbol: str
    :param date: 日期
    :type date: str
    :param time: 默认 time=0，则为当天的排行；如 time="16"，则为 date 的 16 点的热门股票排行
    :type time: str
    :return: 股东人数及持股集中度
    :rtype: pandas.DataFrame
    """
    symbol_map = {
        "全部": "all",
        "A股": "ab",
        "港股": "hk",
        "美股": "us",
    }
    url = "https://finance.pae.baidu.com/vapi/v1/hotrank"
    params = {
        "tn": "wisexmlnew",
        "dsp": "iphone",
        "product": "stock",
        "day": date,
        "hour": time,
        "pn": "0",
        "rn": "1000",
        "market": symbol_map[symbol],
        "type": "day" if time == 0 else "hour",
        "finClientType": "pc",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    temp_df = pd.DataFrame(
        data_json["Result"]["body"], columns=data_json["Result"]["header"]
    )
    # temp_df["综合热度"] = pd.to_numeric(temp_df["综合热度"])
    # temp_df["排名变化"] = pd.to_numeric(temp_df["排名变化"])
    # temp_df["是否连续上榜"] = pd.to_numeric(temp_df["是否连续上榜"])
    return temp_df


def xue_qiu_cube_found():
    """
    雪球组合榜单
    :return:
    """
    url = 'https://xueqiu.com/cube/center/cube_found/hot_symbol_list.json?page=1&size=100'
    return xue_qiu_board(url)


def xue_qiu_point_found():
    """
    雪球关注榜单
    :return:
    """
    url = 'https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=1&size=100&order=desc&order_by=value&_=1659000637623&type=hot_follow&x=0.5'
    return xue_qiu_board(url)


def ths_24_hot():
    url = 'https://eq.10jqka.com.cn/open/api/hot_list/v1/hot_stock/a/day/data.txt'
    return ths_billboard(url)


def eastmoney_hot_rank_up(code):
    hot_ranks = eastmoney_hot_ranks(code)
    rank_div = hot_ranks[-2] - hot_ranks[-1]
    if rank_div > 0:
        return True
    return False


def tgb_top20_hot_rank():
    stocks = list()
    stock_hot_tgb_df = ak.stock_hot_tgb()
    stock_hot_tgb = stock_hot_tgb_df['个股代码'].values
    for stock in stock_hot_tgb:
        code = code_remove_sz_sh_symbol(stock)
        stocks.append(code)
    return stocks


def eastmoney_hot_ranks(code):
    full_code = code_to_sz_sh_symbol(code)
    stock_hot_rank_detail_em_df = ak.stock_hot_rank_detail_em(symbol=full_code)
    ranks = stock_hot_rank_detail_em_df['排名'].values
    return ranks


def eastmoney_hot_rank_top():
    stock_hot_rank_em_df = ak.stock_hot_rank_em()
    hot_stocks = stock_hot_rank_em_df['代码'].tolist()
    stocks = list()
    for hot_stock in hot_stocks:
        code = symbol_remove_SZ_SH_front(hot_stock)
        stocks.append(code)
    return stocks


@retry(tries=10, delay=10, backoff=1)
def hot_pop_stocks(code_list):
    """
    人气面
    """
    hot_pops = list()

    baidu_hot_stocks = baidu_hot_search_today()
    eastmoney_hot_stocks = eastmoney_hot_rank_top()
    tgb_top20_hot_rank_stocks = tgb_top20_hot_rank()
    ths_24_hot_stocks = ths_24_hot()

    for code in code_list:
        is_true = eastmoney_hot_rank_up(code)
        if is_true:
            hot_pops.append(code)
        if code in baidu_hot_stocks:
            hot_pops.append(code)
        if code in eastmoney_hot_stocks:
            hot_pops.append(code)
        if code in tgb_top20_hot_rank_stocks:
            hot_pops.append(code)
        if code in ths_24_hot_stocks:
            hot_pops.append(code)

    # 去除重复
    hot_pops = list(set(hot_pops))
    return hot_pops
